package xyz.naokeziteng.level2cache.util;

import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

/**
 * @author hawk
 * @date 2022/8/2
 * @desc spring el 表达式解析
 **/
public class SpringELUtils {

    /**
     * 解析el表达式
     *
     * @param expression 表达式
     * @param method     方法
     * @param args       参数
     * @return v
     */
    public static String parseExpression(String expression, Method method, Object[] args) {
        //获取被拦截方法参数名列表
        LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNameArr = discoverer.getParameterNames(method);
        if (paramNameArr == null) {
            return expression;
        }
        //SPEL解析
        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < paramNameArr.length; i++) {
            context.setVariable(paramNameArr[i], args[i]);
        }
        return parser.parseExpression(expression).getValue(context, String.class);
    }
}
